<template>
  <view>
    <view style="padding: 1.5rem;padding-top: 6rem;text-align: center">
      <image style="width: 100px; height: 100px; background-color: #fff;margin-bottom: 1rem;" mode="aspectFit"
             src="/static/logo.png"></image>
      <view style="margin-bottom: 10px;">
        <span style="font-size:20px">{{ settings['login.site_name'] || '后台管理系统' }}</span>
      </view>
      <view style="margin-bottom: 10px;">
        <span style="font-size:16px">账号/密码登录</span>
      </view>
    </view>
    <view class="loginForm">
      <view style="margin-bottom: 1rem;">
        <uni-forms ref="baseForm" :modelValue="baseFormData" :rules="customRules">
          <uni-forms-item label="用户名" required name="username">
            <uni-easyinput v-model="baseFormData.username" placeholder="请输入用户名"/>
          </uni-forms-item>
          <uni-forms-item label="密码" required name="password" >
            <uni-easyinput v-model="baseFormData.password" type="password" placeholder="请输入密码"/>
          </uni-forms-item>
          <uni-forms-item label="验证码" required name="captcha" v-if="settings['base.captcha_state']">
            <view>
              <uni-easyinput v-model="baseFormData.captcha" placeholder="请输入验证码"
                             style="width: calc(100% - 120px);position: absolute;"/>
              <image :src="codeInfo.image_base" mode="" class="code-img" @click="handleGetCode"></image>
            </view>
          </uni-forms-item>
        </uni-forms>
        <view style="margin-top: 30px;">
          <button v-if="!agreement" type="primary" style="border-radius: 30px" @click="clickNotAgreement"
          >登录
          </button>
          <button v-else type="primary" style="border-radius: 30px" @click="login">登录
          </button>
        </view>
      </view>
      <view style="text-align: center">
        <view style="font-size: 12px">
          <checkbox :checked="agreement" value="1" style="transform:scale(0.6)" color="#cccccc"
                    @click="clickCheckbox"/>
          我己阅读并同意<span style="color:#639DB7;" @click="clickTermsService">《用户服务协议》</span>和<span
            style="color:#639DB7;" @click="clickPrivacy">《隐私政策》</span>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {
  API_URL
} from "@/env";
import w_md5 from "../../js_sdk/zww-md5/w_md5.js"
export default {
  name: "login",
  components: {
    w_md5
  },
  data() {
    return {
      agreement: false,
      // 基础表单数据
      baseFormData: {
        username: '',
        password: '',
        captcha: ''
      },
      loginUid: '',
      codeInfo: {},
      customRules: {
        username: {
          rules: [{
            required: true,
            errorMessage: '用户名不能为空'
          }]
        },
        password: {
          rules: [{
            required: true,
            errorMessage: '密码不能为空'
          }]
        },
        captcha: {
          rules: [{
            required: true,
            errorMessage: '验证码不能为空'
          }]
        },
      },
      settings: uni.getStorageSync('third_settings') || {},
      type: '',
    }
  },
  onReady() {
    // 设置自定义表单校验规则，必须在节点渲染完毕后执行

  },
  onLoad: async function (option) {
    if (uni.getStorageSync('is_webview')) {
      webUni.reLaunch({
        url: '/pages/index/index'
      })
      return
    }
    this.loginUid = option.login_uid || ''
    this.type = option.type || ''
    const token = uni.getStorageSync('token') || '';
    if (token) {
      // 如果token 存在则跳转到index 页面
      uni.reLaunch({
        url: this.loginUid ? ('/pages/index/index?login_uid=' + this.loginUid) : '/pages/index/index'
      })
      return
    }
    this.handleGetCode()
  },
  mounted() {
  },
  methods: {
    // 登录
    login() {
      this.$refs['baseForm'].validate().then(res => {
        console.log('success', res);
        uni.showLoading({
          title: '登录中...'
        });
        uni.request({
          url: API_URL + 'api/dvadmin_third/third_login/', //仅为示例，并非真实接口地址。
          data: {
            ...res,
            captchaKey: this.codeInfo.key,
            password: w_md5.hex_md5_32(res.password),
            type: this.type,
            login_uid: this.loginUid
          },
          method: 'post',
          success: (res) => {
            uni.hideLoading()
            if (res.data.code === 2000) {
              uni.setStorageSync('token', res.data.data.access);
              uni.showToast({
                title: `登录成功`
              })
              uni.reLaunch({
                url: this.loginUid ? (`/pages/index/index?login_uid=${this.loginUid}&type=${this.type}`) : '/pages/index/index'
              })
            } else {
              uni.showToast({
                icon: 'none',
                duration: 2000,
                title: res.data.msg
              })
              this.handleGetCode()
            }
          }
        });

      }).catch(err => {
        console.log('err', err);
      })
    },
    // 未勾选时事件
    async clickNotAgreement() {
      if (!this.agreement) {
        uni.showToast({
          title: '请先同意协议条款',
          icon: 'none',
          duration: 2000
        });
      }
    },
    clickCheckbox() {
      this.agreement = !this.agreement
    },
    clickTermsService() {
      uni.navigateTo({
        url: '/pages/clause/termsService'
      })
    },
    clickPrivacy() {
      uni.navigateTo({
        url: '/pages/clause/privacy'
      })
    },
    /**
     * 获取图形验证码
     */
    handleGetCode() {
      if (!this.settings['base.captcha_state']) return
      var _this = this
      uni.request({
        url: API_URL + 'api/captcha/', //仅为示例，并非真实接口地址。
        success: (res) => {
          if (res.data.code === 2000) {
            _this.codeInfo = res.data.data
          }
        }
      });
    }
  }
}
</script>

<style scoped lang="scss">
#page {
  background-color: #ffffff;
}

::v-deep .center {
  text-align: center;
  margin-top: 0.5rem;

  .u-text {
    justify-content: center !important;
  }
}

.loginForm {
  margin: 1.5rem;
  margin-top: 5vh;
}

.code-img {
  display: block;
  width: 100px;
  height: 37px;
  position: absolute;
  right: 0;
}
</style>
